<template>
  <div class="login-modal">
    <!-- 不点x也会隐藏  因为事件冒泡啦 -->
    <div class="mask" @click="changeisShowLoginModal(false)"></div>
    <div class="login-box">
      <img class="close" @click="changeisShowLoginModal(false)" src="@/assets/img/close.png" alt="" />
      <ul class="title">
        <li :class="isShowForm == true ? 'active' : ''" @click="isShowForm = true">手机号码登录</li>
        <li style="margin: -2px 10px 0; cursor: none">|</li>
        <li :class="isShowForm == false ? 'active' : ''" @click.stop="showQrCode">微信扫码登录</li>
      </ul>
      <div class="body">
        <div class="form" v-show="isShowForm">
          <div class="input-group">
            <input type="text" name="" placeholder="请输入手机号" v-model="PhoneNumber" id="" />
          </div>
          <div class="input-group">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
            ></slide-verify>
          </div>
          <div class="input-group">
            <input type="text" name="" v-model="code" placeholder="验证码" id="" />
            <!--        <div class="btn get-code">{{ msg }}{{ count }}</div> -->
            <!-- 数字显示 -->
            <button class="btn get-code" v-show="isShowCount" @click="getCode">获取验证码</button>
            <button class="btn get-code" v-show="!isShowCount">{{ count }}</button>
          </div>
          <div class="btn" @click="submitLogin">登录</div>
          <h2></h2>
        </div>
        <!-- 微信二维码 -->
        <div class="qrcode" v-show="!isShowForm" id="weixin"></div>
      </div>
    </div>
  </div>
</template>
 
<script>
import { mapActions, mapMutations } from 'vuex'
import { third, fourth, BinddingAPI } from '@/request/api'
/* 手机正则封装的导入 */
import { validatePhoneNumber } from '@/utils/index'

export default {
  data() {
    return {
      isShowForm: true,
      msg: '向右滑动',
      /* 滑动图数组  */
      arr: [
        require('../assets/img/integral-01.9386d4bf.png'),
        require('../assets/img/integral-02.150d92a1.png'),
        require('../assets/img/integral-03.9870f3f1.png'),
        require('../assets/img/integral-04.afadcbdf.png')
      ],
      PhoneNumber: '',
      count: 5,
      /* 倒计时显示 */
      isShowCount: true,
      //验证码
      code: ''
    }
  },
  methods: {
    /* 二维码盒子 */
    showQrCode() {
      this.isShowForm = false
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this
      new WxLogin({
        id: 'weixin',
        appid: 'wx67cfaf9e3ad31a0d', // 这个appid要填死
        scope: 'snsapi_login',
        // 扫码成功后重定向的接口
        redirect_uri: 'https://sc.wolfcode.cn/cms/wechatUsers/shop/PC',
        // state填写编码后的url
        state: encodeURIComponent(window.btoa('http://127.0.0.1:8080' + _this.$route.path)),
        // 调用样式文件
        href: 'data:text/css;base64,Lyog6ZqQ6JeP5LqM57u056CB5Lit55qE5paH5a2XICovDQouaW1wb3dlckJveCAudGl0bGUsDQouaW1wb3dlckJveCAuaW5mbyB7DQogICAgZGlzcGxheTogbm9uZTsNCn0='
      })
    },
    ...mapMutations({
      changeisShowLoginModal: 'showLoginModal/changeisShowLoginModal',
      changeisLoginStatusModal: 'loginStatus/changeisLoginStatusModal',
      isToastStatusModal: 'toastShow/isToastStatusModal'
    }),
    ...mapActions({
      asyncisToastStatusModal: 'toastShow/asyncisToastStatusModal',
      //得到后台的用户信息
      asyncChangeUserInfo: 'userInfo/asyncChangeUserInfo'
    }),
    /* 倒计时的封装 */
    daijishi() {
      this.isShowCount = false
      let time = setInterval(() => {
        this.count--
        if (this.count <= 0) {
          this.isShowCount = true
          this.count = 5
          clearInterval(time)
        }
      }, 1000)
    },
    toVerify() {
      if (!validatePhoneNumber(this.PhoneNumber)) {
        // alert('请输入正确的手机格式')
        this.asyncisToastStatusModal({
          isshow: true,
          msg: '请输入正确的手机格式',
          type: 'success'
        })

        return
      }
      /* 滑动判断  */
      if (this.msg == '向右滑动' || this.msg == '再试一次') {
        // alert('请正解滑动滑块')
        this.asyncisToastStatusModal({
          isshow: true,
          msg: '请正解滑动滑块',
          type: 'danger'
        })
        return
      }
      return true
    },
    async getCode() {
      /* 点击判断手机格式是否正确 */
      // let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      // if (!reg.test(this.PhoneNumber)) {
      //   alert('请输入正确的手机格式')
      //   return
      // }

      /* 发送请求 */
      /* 得到toVerify返回值  函数里面的返回值才另一个函数里面是不起作用的，只在当前函数有用  */
      let flag = this.toVerify()
      let res = await third({
        phone: this.PhoneNumber
      })
      console.log('发送短信验证码：', res)
      if (!res) return
      this.daijishi()
      // if (res.data.code != 0) {
      //   this.daijishi()
      // }
    },
    async submitLogin() {
      /* 手机号和滑块的判断  */
      let flag = this.toVerify()
      if (!flag) return
      // let res = await third({
      //   phone: this.PhoneNumber
      // })
      //倒计时的判断
      // console.log(res)
      // if (res.data.code != 0) {
      //   this.isShowCount = false
      //   let time = setInterval(() => {
      //     this.count--
      //     if (this.count <= 0) {
      //       this.isShowCount = true
      //       this.count = 5
      //       clearInterval(time)
      //     }
      //   }, 1000)
      // }
      //验证码不能为空
      if (!this.code.trim()) {
        /*      alert('验证码不能为空') */
        return
      }
      /* 扫码登录时第一次会输入手机号，会存uuid */
      let uuid = localStorage.getItem('uuid')
      let res1 = null
      if (uuid) {
        /* 发送请求  微信绑定 */
        res1 = await BinddingAPI({
          verifyCode: this.code,
          phone: this.PhoneNumber,
          uuid
        })
      } else {
        res1 = await fourth({
          verifyCode: this.code,
          phone: this.PhoneNumber
        })
      }
      /* 发送请求  得到登录的token值   */

      /* 对响应做一个判断 */
      if (!res1) return
      console.log(res1)
      /*      alert('登录成功') */
      /* changeisShowLoginModal */
      localStorage.setItem('x-auth-token', res1.data['x-auth-token'])
      //登录按钮消息，购物车出现    登录保存token值  判断是否登录
      this.changeisLoginStatusModal(true)
      /* 模态框消失 */
      this.changeisShowLoginModal(false)
      /*       changeisLoginStatusModal */
      /* 绑定 清除code */
      uuid && this.$router.push(this.$route.path)
      localStorage.removeItem(uuid)
      this.asyncChangeUserInfo()
      /* */
      /* 点击登录按钮执行这里的代码 */
      /* 手机号码的验证 */
      // let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      // if (!reg.test(this.PhoneNumber)) {
      //   alert('请输入正确的手机吗')
      //   return
      // }
      // /* 手机验证码的验证 */
      // if (this.msg == '再右滑动' || this.msg == '再试一次') {
      //   alert('请拖动滑块')
      //   return
      // }
      // /* 倒计时验证 */
      // let time = setInterval(() => {
      //   this.count--
      //   if (this.count <= 0) {
      //     this.count = 5
      //     clearInterval(time)
      //   }
      // }, 1000)
      // alert('登录成功')
      /* 做登录验证 */
    },
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1)
      this.msg = 'login success, 耗时 ' + ms + 's'
    },
    // 拼图失败
    onFail() {
      this.onRefresh() // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = '再试一次'
    }
  }
}
</script>
 
<style lang = "less" scoped>
#weixin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: -60px;
}
.login-modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;

  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url('../assets/img/login-box-bg.png');
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    .close {
      position: absolute;
      right: 62px;
      top: 20px;
      cursor: pointer;
    }
    .title {
      display: flex;
      justify-content: center;
      padding: 40px;
      font-size: 18px;
      color: #ccc;
      li {
        cursor: pointer;
      }
      .active {
        color: #333;
      }
    }
    .body {
      width: 360px;
      height: 200px;
      margin: 25px auto 0;
      .form {
        .btn {
          background-color: blue;
          height: 50px;

          text-align: center;
          font-size: 18px;
          cursor: pointer;
        }
        .input-group {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
          .get-code {
            width: 100px;
            padding: 0 10px;
            font-size: 16px;
            margin-left: 10px;
          }
          input {
            flex: 1;
            box-sizing: border-box;
            height: 50px;
            padding-left: 20px;
          }
        }
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>